#include <pthread.h>
#include <iostream>
#include <map>
#include <string>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "CommFormat.h"
#include "socket_lib/ClientSocket.h"
#include "socket_lib/SocketException.h"

#include <sys/types.h>
#include <sys/stat.h>   //mkfifo()
#include <fcntl.h>      //O_WRONLY O_RDONLY
#include <unistd.h>
#include <time.h>

#define FIFOPATH1 "/home/xbq/dev/test/select/fifo1"
//#define FIFOPATH2 "/home/xbq/dev/test/select/fifo2"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

using namespace std;

void* timer5 (void*)
{
	int writefd;
	string str = "nihao\n\r";
	struct timespec delay;
	delay.tv_sec = 5;
	delay.tv_nsec = 0;
	writefd = open(FIFOPATH1, O_RDONLY);
	
	while (1) {
		//pthread_delay_np( &delay );
		sleep(5);
		//writefd = open(FIFOPATH1, O_WRONLY);
		cout << __LINE__ << endl;
		write(writefd, str.c_str(), str.length());
	}
}

void* select_thread (void*)
{

}

int main (void)
{
	fd_set fdset;
	int maxfdp1;
	int readfd;
	string buff;
	try {
		pthread_t tid1;
		mkfifo(FIFOPATH1, FILE_MODE);
		pthread_create(&tid1, NULL, timer5, NULL);
		pthread_join(tid1, 0);

		ClientSocket cli_sock1("192.168.237.57", 2000);
		ClientSocket cli_sock2("192.168.237.57", 2000);
		//ClientSocket cli_sock3("192.168.237.57", 2002);
		//map<CommKey, ClientSocket> sock_cli_arr;
		//cli_sock1 << "d";
		//cout << sizeof(fdset) << endl;
		//cout << FD_SETSIZE << endl;
		//cout << __LINE__ << ":" << sizeof(VlinkInfoMsg) << sizeof(VlinkStateInfo) << sizeof(in6_addr) << sizeof(short) << endl;
		cout << __LINE__ << endl;
		FD_ZERO(&fdset);
		readfd = open(FIFOPATH1, O_RDONLY);
		cout << readfd << endl;
		if (readfd < 0) 
		{
			perror ("error: ");
		}
		while (true)
		{
			FD_SET(cli_sock1.sockfd(), &fdset);
			FD_SET(cli_sock2.sockfd(), &fdset);
			FD_SET(readfd, &fdset);
			maxfdp1 = max( readfd, max(cli_sock1.sockfd(), cli_sock2.sockfd())) + 1;
			cout << maxfdp1 << endl;
			select(maxfdp1, &fdset, NULL, NULL, NULL);

			if ( FD_ISSET(cli_sock1.sockfd(), &fdset) )
			{
				cli_sock1 >> buff;
				cout << buff << "1" << endl;
			}
			if ( FD_ISSET(cli_sock2.sockfd(), &fdset) )
			{
				cli_sock2 >> buff;
				cout << buff << "2" << endl;
			}
			if ( FD_ISSET(readfd, &fdset) )
			{
				cout << "5 sec passed." << endl;
				//read(readfd, );
			}
		}
	}
	catch (SocketException& e)
	{
		cout << "Exception was caught: " << e.description() << endl;
	}
	return 0;
}

